/**
* ShieldJSSelect
* @fileOverview 下拉框，需要依赖shield.main.js以及tool/doT.js，templ/select.html
* @author kevin
* @email donggongai@126.com
* @version 1.0
* @date 2018-3-16
*/
;(function($){
	/**
	* @author kevin
	* @constructor ShieldJSSelect
	* @description 菜单样式
	* @see The <a href="#">kevin</a>
	* @example
	*	$(".nav").ShieldJSSelect();
	* @since version 1.0
	*/
	$.fn.ShieldJSSelect = function(options){
		debug(this);
		if (this.length > 0) {
			/**
			 * @description {Json} 设置参数选项
			 * @field
			 */
			var options = $.extend({}, $.fn.ShieldJSSelect.defaults, options);
			/**
			 * @description 处理函数
			 */
			return this.each(function() {
				var thisSelectE = $(this);
				var templid = thisSelectE.attr("templid")||'default'; //模板id
				var defaultV =  thisSelectE.attr("v"); //默认值
				var optionEles = thisSelectE.children();
				//var replaceOptionHtml ='';
				var selectEdEle = null; //选中元素
				var templData = {}; //模板数据
				templData.options = new Array();
				
				var dealOptionEles = function(eles, optionsData) {
					eles.each(function(){
						var optionEle = $(this);
						var optionOjb = {};
						var name = optionEle.text();
						var value = optionEle.val();
						optionOjb.name = name;
						optionOjb.value = value;
						optionOjb.type = "option";
						var optionClass="";
						if (optionEle.is("option")) {
							//replaceOptionHtml += '<dd shield-value="'+ value +'" class="';
							if (!value) { //第一个，无实际含义，tips，样式追加
								optionClass +="shield-select-tips ";
							}
							if (hasAttr(optionEle, "disabled")) { //不可用，样式追加
								optionClass += ShieldJS.css.DISABLED+" ";
							} 
							//replaceOptionHtml += optionClass;
							//replaceOptionHtml += ' ">'+ name +'</dd>';
							if (hasAttr(optionEle, "selected")) { //选中处理
								selectEdEle = optionEle;
							} else if(value == defaultV){
								selectEdEle = optionEle;
							}
		                } else if (optionEle.is("optgroup")) { //分组元素
		                	optionOjb.type = "optgroup";
		                	optionOjb.name = optionEle.attr("label");
		                	optionOjb.options = new Array();
		                	//replaceOptionHtml += '<dt>'+optionEle.attr("label")+'</dt>';
		                	dealOptionEles(optionEle.find("option"), optionOjb.options);
						}
						optionOjb.classes = optionClass;
						optionsData.push(optionOjb); 
					});
		        }
				dealOptionEles(optionEles, templData.options);
				var firstE = optionEles.eq(0);
				templData.tipName = firstE.text();
				templData.placeholder = firstE.text();
//				var replaceHtml = 
//					'<div class="shield-unselect shield-form-select">'
//					+'	<div class="shield-select-title">'
//					+'		<input type="text" placeholder="'+firstE.text()+'" value="'+ firstE.text() +'" readonly'
//					+'			class="shield-input shield-unselect"> <i'
//					+'				class="shield-edge"></i>'
//					+'	</div>'
//					+'	<dl class="shield-anim shield-anim-upbit">'
//					+ replaceOptionHtml
//					+'	</dl>'
//					+'</div>';
				//调用模板
				var conText = doT.template(ShieldJS.templ.SELECT[templid])(templData);
				ShieldJS.debug(conText);
				//replaceHtml = conText; 
				thisSelectE.after(conText);
				//事件处理
				var shieldSelectEle = thisSelectE.next();
				var shieldSelectTitleInputEle = shieldSelectEle.find(".shield-select-title>.shield-input");
				shieldSelectTitleInputEle.click(function() {
					shieldSelectEle.toggleClass("shield-form-selected");
					shieldSelectEle.find(".shield-hide").removeClass("shield-hide"); 
					return false; //阻止冒泡
				});
				shieldSelectEle.on("click", "dd,dt", function() {
					var $this = $(this);
					if ($this.is("dd")) { //只处理普通选项，不处理组
						if (!$this.hasClass(ShieldJS.css.DISABLED)) {
							$this.siblings("dd."+ShieldJS.css.THIS).removeClass(ShieldJS.css.THIS);
							if (!$this.hasClass("shield-select-tips")) { //非提示项
								$this.addClass(ShieldJS.css.THIS);
							}
							shieldSelectTitleInputEle.val($this.text());
							thisSelectE.val($this.attr("shield-value")).triggerHandler("change",["false"]); //真实元素赋值,并触发绑定的change事件，false表示不再执行选中元素的点击防止死循环
							if (typeof(console) != "undefined"){
								console.log("select选中=="+thisSelectE.val());
							} 
							shieldSelectEle.removeClass("shield-form-selected"); //点击完成后取消显示
						}
		            }
					return false; //阻止冒泡
				});
				$(document).click(function() {
					shieldSelectEle.removeClass("shield-form-selected");
		        });
				if (selectEdEle) { //选中处理
					shieldSelectEle.find("dd[shield-value='"+selectEdEle.val()+"']").click();
				}
				if (hasAttr(thisSelectE, "shield-search")) { //可搜索,如果覆盖样式可能不兼容
					shieldSelectTitleInputEle.removeAttr("readonly");
					shieldSelectTitleInputEle.removeClass("shield-unselect");
					shieldSelectTitleInputEle.keyup(function(event){
						var inputVal = $.trim($(this).val());
						shieldSelectEle.find("dd,dt").each(function() {
							var $this = $(this);
							$this.addClass("shield-hide");
							if ($this.text().indexOf(inputVal) > -1) { //包含内容
								$this.removeClass("shield-hide");
								if ($this.prev().is("dt")) { //分组元素
									$this.prev().removeClass("shield-hide");
					            }
							}
						});
					});
				} else {
					shieldSelectTitleInputEle.prop("readonly", true);
					shieldSelectTitleInputEle.addClass("shield-unselect");
				}
				thisSelectE.hide(); //隐藏原始元素
				thisSelectE.change(function(event, changeShieldValue) { //值变化值将其赋值给处理元素
					changeShieldValue = changeShieldValue||"true";
					if (changeShieldValue=="true") { //防止死循环
						var $this = $(this);
						shieldSelectEle.find("dd[shield-value='"+$this.val()+"']").click();
	                    
                    }
                });
			});
        }
	};
	/**
	* @description {Json} 默认参数
	* @field
	*/
	$.fn.ShieldJSSelect.defaults = {
		// 鼠标悬浮的菜单样式
		barClass : 'shield-nav-bar'
		// 条目样式
	    ,itemClass : 'shield-nav-item'
	    // 竖向样式
	    ,treeClass : 'shield-nav-tree'
	    // 竖向选中样式
		,treeItemdClass : 'shield-nav-itemed'
		// 展开收起样式，存在子菜单
		,moreClass : 'shield-nav-more'
		// 展开收起样式,显示子菜单时出现
		,moredClass : 'shield-nav-mored'
		// 子菜单样式
		,childClass : 'shield-nav-child'
		// icon图标样式
		,iconClass : 'shield-icon'
	};
	$.fn.ShieldJSSelect.filter = function(dealEle) {
		var showName = "shield-select元素";
		if (dealEle.length > 0) {
			dealEle.each(function() {
				var $this = $(this);
				if (!$this.is("select")) {
					dealEle = dealEle.not($this);
					ShieldJS.error("检测到" + showName + "不是select表单元素，请修改！"+$this.prop("outerHTML"));
					return false; //true=continue，false=break。 
				}
	        });
		}
		return dealEle;
	}
	/**
	* @description 输出选中对象的个数到控制台
	* @param {jQueryObject} $obj 选中对象
	*/
	function debug($obj) {
		if (window.console && window.console.log)
			window.console.log('ShieldJSPage selection count: ' + $obj.size());
	};
})(jQuery);